package io.github.consoles.dsa;

import java.util.Iterator;

/**
 * Created by yiihua-013 on 17/2/9.
 * 用环形链表实现Queue。环形链表也是一条链表，只是没有任何结点链接为空，且只要链表非空则last.next的值就为first。只能使用一个Node类型的实例变量（last）
 */
public class CircleQueue<Item> implements Iterable<Item> {

    private class Node {
        Item item;
        Node next;

        Node(Item item) {
            this.item = item;
        }
    }

    private Node last;

    public boolean isEmpty(){
        return last == null;
    }

    public void enqueue(Item item) {
        Node node = new Node(item);
        if (isEmpty()) {
            last = node;
            node.next = node;
        } else {
            node.next = last.next;
            last.next = node;
            last = node;
        }
    }

    public Item dequeue(){
        if (isEmpty()) return null;

        Item item = last.next.item; // 找队头
        if (last.next == last) last = null;
        else last.next = last.next.next;
        return item;
    }

    private class CircleIterator implements Iterator<Item> {

        private Node first;

        /**
         * 初始化头结点
         */
        public CircleIterator() {
            if (last == null) first = null;
            else first = last.next;
        }

        @Override
        public boolean hasNext() {
            return first != null;
        }

        @Override
        public Item next() {
            Item item;
            if (last == last.next) {
                first = null;
                item = last.item;
            } else {
                item = first.item;
                first = first.next;
                if (first == last.next) first = null;
            }
            return item;
        }
    }

    @Override
    public Iterator<Item> iterator() {
        return new CircleIterator();
    }
}
